package com.zhenyi.youqu.admin.index;

import java.util.Date;

import com.cjw.model.DBMap;
import com.jfinal.aop.Clear;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.youqu.common.model.YqShopUser;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;

public class AuthController extends YQAdminController {

	@Clear
	public void index() {
		if (StrKit.notBlank(getPara("state"))) {
			String state = URLUtil.decode(getPara("state"));
			setAttr("URL", state);
		}
		// if (StrKit.notBlank(AuthUtils.getTokenUid(this))) {
		// redirect("");
		// }
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/yq/admin/login.html");
	}

	@Clear
	public void login() {
		String account = getPara("account");
		String password = getPara("password");
		if (StrKit.isBlank(account)) {
			renderFailure(500, "请输入账号");
			return;
		}
		if (StrKit.isBlank(password)) {
			renderFailure(500, "请输入密码");
			return;
		}

		try {
			String key = getSessionAttr("key");
			password = AESUtils.decrypt(key, password);
			if (password == null) {
				renderFailure(500, "解密失败,请刷新重试");
				return;
			}

			// if (!account.equals(PropKit.get("YQ_ADMIN_ACCOUNT", "admin"))
			// || !password.equals(PropKit.get("YQ_ADMIN_PASSWORD", "admin"))) {
			// renderFailure(500, "账号/密码错误");
			// return;
			// }
			DBMap map = new DBMap();
			map.put("account", account);
			map.put("password", password);
			YqShopUser user = YqShopUser.dao.searchFirst(map);
			if (user == null) {
				renderFailure(500, "账号/密码错误");
				return;
			}
			if (user.getStatus().equals(0)) {
				renderFailure(500, "账号已被禁用");
				return;
			}
			user.setLoginTime(new Date());
			user.update();

			String token = AuthUtils.login(String.valueOf(user.getId()), this);

			String redirectUrl = user.getRole().equals(4) ? "/yq/admin/order/recordList" : "/yq/admin/product/list";
			renderSuccess(redirectUrl);
		} catch (Exception e) {
			e.printStackTrace();
			renderFailure("账号/密码错误");
			return;
		}
	}

	public void logout() {
		AuthUtils.logout(this);
		redirect("/yq/admin/auth");
	}
}
